package com.goodflower.goodflower.chang_mac;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.goodflower.goodflower.FlowerActivity;
import com.goodflower.goodflower.R;
import com.goodflower.goodflower.creat_flower.Creat_flower_four;
import com.goodflower.goodflower.creat_mac.Creat_mac_five;
import com.goodflower.goodflower.info.Info;
import com.goodflower.goodflower.util.UploadImage;

import java.io.File;
import java.io.IOException;

public class Change_myflower_image extends AppCompatActivity {
    private ImageView creat_flower_image;
    private Button btn_creat_flower_takephoto;
    private Button btn_creat_flower_choose;
    private Button btn_creat_flower_four_next;

    private Uri imageUri;//图片Uri
    private String lujing;

    private AsyncTask asyncTask;
    private String actionUrl = "http://"+Info.server_ip+"/huahua/phone_setmacimage.php?";
    private String flower_mac;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.creat_flower_four);
        Intent intent = getIntent();
        flower_mac = intent.getStringExtra("flower_mac");
        //获取控件
        creat_flower_image = (ImageView) findViewById(R.id.creat_flower_image);
        btn_creat_flower_takephoto = (Button) findViewById(R.id.btn_creat_flower_takephoto);
        btn_creat_flower_choose = (Button) findViewById(R.id.btn_creat_flower_choose);
        btn_creat_flower_four_next = (Button) findViewById(R.id.btn_creat_flower_four_next);
        /****拍照***/
        btn_creat_flower_takephoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(Change_myflower_image.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(Change_myflower_image.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
                } else {
                    takephoto();
                }


            }
        });
        btn_creat_flower_choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(Change_myflower_image.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(Change_myflower_image.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    openAlbum();
                }
            }
        });
        btn_creat_flower_four_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initTask();
                asyncTask.execute();
            }
        });
    }
    /***
     * 拍照用到的函数
     **/
    private void takephoto() {
        File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
        lujing = getExternalCacheDir() + "/output_image.jpg";
        Log.d("tu", lujing);
        if (outputImage.exists()) {
            outputImage.delete();
        }
        try {
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(Change_myflower_image.this, "com.goodflower.goodflower.provider", outputImage);

        } else {
            imageUri = Uri.fromFile(outputImage);
        }
        //启动相机

        Intent intent = new Intent();
        intent.setAction("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, 1);
    }

    private void openAlbum() {//打开相册
        Intent intent = new Intent();
        intent.setAction("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, 2);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(Change_myflower_image.this, "没有权限", Toast.LENGTH_LONG).show();
                }
                break;
            case 2:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    takephoto();
                } else {
                    Toast.makeText(Change_myflower_image.this, "没有权限", Toast.LENGTH_LONG).show();
                }
                break;
            default:
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    try {

                        // Glide.with(Creat_mac_five.this).load(imageUri).into(image);
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        creat_flower_image.setImageBitmap(bitmap);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        handleImageOnKitKat(data);
                    } else {
                        handleImageBeforeKitKat(data);
                    }
                }
                break;

            default:
                break;
        }
    }

    /***********************/
    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            imagePath = uri.getPath();
        }
        lujing = imagePath;
        displayImage(imagePath);
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        lujing = imagePath;
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Glide.with(Change_myflower_image.this).load(imagePath).into(creat_flower_image);
            Log.d("tu", imagePath);
        } else {
            Toast.makeText(Change_myflower_image.this, "抱歉出了点问题", Toast.LENGTH_LONG).show();
        }
    }

    /*****
     * 网络部分
     ****/

    private void initTask() {
        final ProgressDialog progressDialog = new ProgressDialog(Change_myflower_image.this);
        progressDialog.setTitle("请稍等");
        progressDialog.setMessage("正在创建新的花园");
        asyncTask = new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {
                String myactionUrl = actionUrl +"mac="+flower_mac+"&username="+ Info.current_user_name;
                String response = UploadImage.uploadFile(new File(lujing), myactionUrl);
                return response;
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // urlString = editText.getText().toString();
                //Toast.makeText(Creat_mac_five.this, "开始上传", Toast.LENGTH_SHORT).show();
                progressDialog.show();
            }

            @Override
            protected void onPostExecute(Object o) {
                super.onPostExecute(o);
                //Toast.makeText(Creat_mac_five.this, (o == null ? "" : o.toString()), Toast.LENGTH_LONG).show();
                //Log.d("shibai", (o == null ? "" : o.toString()));
                if(progressDialog!=null){
                    progressDialog.dismiss();
                }
                Intent intent = new Intent(Change_myflower_image.this, FlowerActivity.class);
                intent.putExtra("yourname",Info.current_user_name);
                startActivity(intent);
            }
        };
    }

}
